/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.members;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.RechargeType;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.entity.enums.UseScene;
import com.qinyeit.serviceapp.service.branchs.BranchDataReleasedServiceImpl;
import com.qinyeit.serviceapp.service.members.MemberCardService;
import com.qinyeit.serviceapp.service.members.MemberCardTypeBranchService;
import com.qinyeit.serviceapp.service.members.RechargeRuleService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.serviceapp.service.pays.DiscountPlanService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.service.members.MemberCardTypeService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * ClassName: MemberCardTypesController <br/>
 * Function: memberCardType [会员卡类型] <br/>
 * date: 2018-12-03 14:58:01 <br/>
 *
 * @author DESKTOP-DHS6NG3
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/members/memberCardTypes")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_memberCardType:read",name ="会员卡类型",deleteAble = false)
public class MemberCardTypesController extends BaseManagementController{

	@Autowired
	private MemberCardTypeService memberCardTypeService;
	@Autowired
	private DiscountPlanService discountPlanService;
	@Autowired
	private DistrictService districtService;
	@Autowired
    private MemberCardTypeBranchService memberCardTypeBranchService;
	@Autowired
    private RechargeRuleService rechargeRuleService;
	@Autowired
    private BranchService branchService;
	@Autowired
    private MemberCardService memberCardService;
	@Autowired
    private BranchDataReleasedServiceImpl branchDataReleasedService;

	private final String [] keys = {"id","name","discountId","hasVipPrice","hasConsumeRecharge","consumePrice","giftPoint","rechargeRule","rechargeType","discountName","pointRule","hasUseRule","useRuleDetail"};

    @RequiresPermissions("management_memberCardType:show")
    @PermissionInfo(code = "management_memberCardType:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        List<MemberCardType> memberCardTypes = memberCardTypeService.findWithSort(searchable);
        DiscountPlan discountPlan = null;
        if (CollectionUtils.isNotEmpty(memberCardTypes)){
            for (MemberCardType cardType : memberCardTypes) {
                if (cardType.getDiscountId()!=null){
                    discountPlan = discountPlanService.findById(cardType.getDiscountId());
                    if (discountPlan!=null){
                        cardType.setDiscountName(discountPlan.getName());
                    }
                }
            }
        }
        return ok("查询成功", JSONUtils.include(memberCardTypes,new Class[]{RechargeType.class}, keys));
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("memberCardType",JSONUtils.include(new MemberCardType(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_memberCardType:create")
    @PermissionInfo(code = "management_memberCardType:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject data, BindingResult bindingResult){
//        if(memberCardTypeService.exists(buildExists(null, "no", memberCardType.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }

        memberCardTypeService.saveData(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute MemberCardType memberCardType){
        return ok("查询成功", JSONUtils.include(memberCardType, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute MemberCardType memberCardType){
        QyMap map=QyMap.NEW();
        map.setv("memberCardType",JSONUtils.include(memberCardType, keys));
        initFormDate(map);
        //门店
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("memberCardTypeId_eq",memberCardType.getId());
        List<MemberCardTypeBranch> branchList = memberCardTypeBranchService.findWithSort(searchable);
        if(CollectionUtils.isNotEmpty(branchList)){
            for (MemberCardTypeBranch branch : branchList) {
                branch.setLabel(branchService.findById(branch.getBranchId()).getName());
            }
        }
        map.setv("branchList",JSONUtils.include(branchList,"branchId","districtId","label"));
        //规则
        searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("categoryId_eq",memberCardType.getId());
        List<RechargeRule> ruleList = rechargeRuleService.findWithSort(searchable);
        map.setv("ruleList",JSONUtils.include(ruleList,"type","rangeStart","rangeEnd","giftMoney","giftPoint"));
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_memberCardType:update")
    @PermissionInfo(code = "management_memberCardType:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@RequestBody JSONObject data,BindingResult bindingResult){
//        if(memberCardTypeService.exists(buildExists(null, "no", memberCardType.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        memberCardTypeService.saveData(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_memberCardType:destory")
    @PermissionInfo(code = "management_memberCardType:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        //判断是否使用
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("type.id_eq",id);
        Long count = memberCardService.count(searchable);
        if (count.intValue()>0){
            return fail("已使用，不允许删除");
        }
        //修改单店的会员卡类型 删除
        memberCardTypeService.updateData(id,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("删除成功", null);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            MemberCardType memberCardType = memberCardTypeService.findById(Long.valueOf(id));
            model.addAttribute(memberCardType);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //折扣方案
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("state_eq", State.NORMAL);
//        searchable.addSearchParam("hasVip_eq",true);
        searchable.addSearchParam("useScene_eq", UseScene.CARDTYPE);
        List<DiscountPlan> planList = discountPlanService.findWithSort(searchable);
        qyMap.setv("planList",JSONUtils.include(planList,"id","type","name"));

        //充值规则类型
        qyMap.setv("rechargeTypes", RechargeType.values());

        //区域门店
//        List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true);
        qyMap.setv("districts",getDistricts());

    }

}